package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 登录功能
     * @param loginForm 登录参数，包含手机号、验证码；或者手机号、密码
     */
    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {

        //校验手机号
        if (RegexUtils.isPhoneInvalid(loginForm.getPhone())) {
            //不符合,返沪错误消息
            return Result.fail("手机号格式错误!" );
        }
        //校验验证码
        String RedisCode = (String) redisTemplate.opsForValue().get(LOGIN_CODE_KEY +loginForm.getPhone());//获取redis中的code
        String input_code = loginForm.getCode(); //用户输入的验证码
        if (RedisCode == null || !RedisCode.equals(input_code)) {
            //不一致，抛异常
            Result.fail("验证码错误!");
        }
        //一致根据手机号查询用户信息
        User user = query().eq("phone", loginForm.getPhone()).one();
        //判断用户是否存在
        if (user == null){
            //不存在，创建新用户并保存
           user = createUserWithPhone(loginForm.getPhone());
        }
        //生成uuit作为登录凭证,响应给前端
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        //使用hoot工具,bean转换为map
        Map<String, Object> map = BeanUtil.beanToMap(userDTO);
        redisTemplate.opsForHash().putAll(LOGIN_USER_KEY + token,map);
        redisTemplate.expire(LOGIN_USER_KEY + token,CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //存在
        return Result.ok(token);
    }

    /**
     * 根据手机号创建新用户
     * @param phone
     * @return
     */
    private User createUserWithPhone(String phone) {

        //创建新用户
        User user = new User();
        user.setPhone(phone);
        user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        user.setCreateTime(LocalDateTime.now());
        //保存用户
        save(user);
        return user;
    }


}
